﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.Logic;
using Portal.Entity;
using Portal.Interface;
using MyLib;
using System.Data;
using System.Threading;

namespace Portal
{
    public partial class SecurityDetail : System.Web.UI.Page
    {
        SecurityLogic _logic = new SecurityLogic();
        ResourceLogic _res = new ResourceLogic();
        ResourceRelationLogic _relation = new ResourceRelationLogic();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtResourceId.Text = Request.QueryString["ResourceId"];

                //如果是编辑隐藏树菜单
                if (!string.IsNullOrEmpty(txtResourceId.Text.Trim()))
                {
                    tvMenu.Visible = false;
                    lblMenu.Visible = false;
                }

                List<string> securityTypes = _logic.GetSecurityTypeList();
                ddlType.DataSource = securityTypes;
                ddlType.DataBind();
                List<ResourceRelationEntity> menus = new List<ResourceRelationEntity>();

                //根据ResourceId加载数据
                LoadData(out menus);

                LoadMenu(menus);


                ddlType_SelectedIndexChanged(sender, e);

                btnSave.Text = Portal.Resources.lang.SecurityDetail_Save;
            }

            txtMember.Attributes.Add("readonly", "readonly");
        }

        void LoadData(out List<ResourceRelationEntity> menus)
        {
            ResourceEntity ety = _res.GetEntity(ConvertUtil.ToInt32(txtResourceId.Text));
            if (ety == null)
            {
                menus = new List<ResourceRelationEntity>();
                return;
            }
            txtName.Text = ety.CNNAME;
            txtMember.Text = ety.EXT07;

            //根据id查询权限菜单
            string str = "select * from com_resourcerelation c where c.ext02=" + Convert.ToInt32(txtResourceId.Text.Trim());
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(str);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ListItem li = new ListItem();
                li.Text = dt.Rows[i]["ext03"].ToString();
                li.Value = dt.Rows[i]["destinationid"].ToString();
                lstboxMember.Items.Add(li);
            }
            txtMemberId.Text = ety.EXT08;
            List<ResourceRelationEntity> list = _relation.GetList(ConvertUtil.ToInt32(txtResourceId.Text));
            menus = list.FindAll(p => p.RELATIONTYPE == "SecurityObject" && p.EXT01 == "Menu");
        }

        void LoadMenu(List<ResourceRelationEntity> menus)
        {
            List<ResourceEntity> list = _res.GetResourceList("Menu");
            //加第一层节点
            List<ResourceEntity> rootlist = list.FindAll(p => p.PARENTID == 0);
            foreach (ResourceEntity ety in rootlist)
            {
                TreeNode tn = new TreeNode();
                if (Portal.Resources.lang.ResourceNameField.ToUpper() == "CNNAME")
                {
                    tn.Text = ety.CNNAME;
                }
                else
                {
                    tn.Text = ety.ENNAME;
                }
                tn.Value = ety.RESOURCEID.ToString();
                if (menus.Exists(p => p.DESTINATIONID == ety.RESOURCEID))
                {
                    tn.Checked = true;
                }
                tn.NavigateUrl = "#";
                tvMenu.Nodes.Add(tn);

                //递归插入子节点
                AddChildNodes(menus, tn, ety.RESOURCEID, list);
            }
            tvMenu.ExpandAll();
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<ResourceRelationEntity> menus = new List<ResourceRelationEntity>();
            List<ResourceRelationEntity> objs = _relation.GetList(ConvertUtil.ToInt32(txtResourceId.Text));
            menus = objs.FindAll(p => p.RELATIONTYPE == "SecurityObject" && p.EXT01 == ddlType.SelectedValue);

            List<ResourceEntity> list = _res.GetResourceList(ddlType.SelectedValue);
            tvData.Nodes.Clear();
            //加第一层节点
            List<ResourceEntity> rootlist = list.FindAll(p => p.PARENTID == 0);
            foreach (ResourceEntity ety in rootlist)
            {
                TreeNode tn = new TreeNode();
                if (Portal.Resources.lang.ResourceNameField.ToUpper() == "CNNAME")
                {
                    tn.Text = ety.CNNAME;
                }
                else
                {
                    tn.Text = ety.ENNAME;
                }
                tn.Value = ety.RESOURCEID.ToString();
                tn.NavigateUrl = "#";
                if (menus.Exists(p => p.DESTINATIONID == ety.RESOURCEID))
                {
                    tn.Checked = true;
                }
                tvData.Nodes.Add(tn);

                //递归插入子节点
                AddChildNodes(menus, tn, ety.RESOURCEID, list);
            }
            tvData.ExpandAll();
        }

        void AddChildNodes(List<ResourceRelationEntity> menus, TreeNode parent, int id, List<ResourceEntity> list)
        {
            List<ResourceEntity> childlist = list.FindAll(p => p.PARENTID == id);
            foreach (ResourceEntity ety in childlist)
            {
                TreeNode tn = new TreeNode();
                if (Portal.Resources.lang.ResourceNameField.ToUpper() == "CNNAME")
                {
                    tn.Text = ety.CNNAME;
                }
                else
                {
                    tn.Text = ety.ENNAME;
                }
                tn.Value = ety.RESOURCEID.ToString();
                tn.NavigateUrl = "#";
                if (menus.Exists(p => p.DESTINATIONID == ety.RESOURCEID))
                {
                    tn.Checked = true;
                }
                parent.ChildNodes.Add(tn);

                AddChildNodes(menus, tn, ety.RESOURCEID, list);
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //判断菜单是否为空或不存在
            if (string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('菜单不能为空!');", true);
                return;
            }
            else
            {

                string str = "select * from com_resource a where a.type='Menu' and a.cnname='" + txtName.Text.Trim() + "'";
                DataTable dts = DataAccess.Instance("BizDB").ExecuteDataTable(str);
                if (dts.Rows.Count <= 0)
                {
                    txtName.Text = "";
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('菜单不存在!');", true);
                    return;
                }
            }

            SecurityLogic logic = new SecurityLogic();
            List<SecurityMemberEntity> members = new List<SecurityMemberEntity>();
            string[] sz = txtMemberId.Text.Split(',');
            foreach (string str in sz)
            {
                SecurityMemberEntity ety = new SecurityMemberEntity();
                string[] ss = str.Split('|');
                ety.MemberId = ConvertUtil.ToInt32(ss[0]);
                if (ss.Length > 1)
                {
                    ety.MemberType = ss[1];
                }
                members.Add(ety);
            }
            List<ResourceEntity> objects = new List<ResourceEntity>();
            List<TreeNode> tns = GetAllCheckedNodes(tvMenu);
            foreach (TreeNode tn in tns)
            {
                ResourceEntity ety = new ResourceEntity();
                ety.TYPE = "Menu";
                ety.RESOURCEID = ConvertUtil.ToInt32(tn.Value);
                ety.CNNAME = tn.Text;
                ety.ENNAME = tn.Text;
                objects.Add(ety);
            }
            tns = GetAllCheckedNodes(tvData);
            foreach (TreeNode tn in tns)
            {
                ResourceEntity ety = new ResourceEntity();
                ety.TYPE = ddlType.SelectedValue;
                ety.RESOURCEID = ConvertUtil.ToInt32(tn.Value);
                ety.CNNAME = tn.Text;
                ety.ENNAME = tn.Text;
                objects.Add(ety);
            }

            int resourceId = 0;

            if (lstboxMember.Items.Count > 0)
            {
                foreach (ListItem li in lstboxMember.Items)
                {
                    resourceId = logic.SaveSecurity(ConvertUtil.ToInt32(txtResourceId.Text), txtName.Text, li.Text, li.Value, members, ddlType.SelectedValue, objects);
                }
            }
            else
            {
                string str = "delete COM_RESOURCERELATION c where c.ext02=" + txtResourceId.Text.Trim();
                DataAccess.Instance("BizDB").ExecuteNonQuery(str);
            }

            //判断菜单是否更改
            if (!string.IsNullOrEmpty(txtResourceId.Text.Trim()))
            {
                string sstr = "select * from com_resource a where a.resourceid=" + txtResourceId.Text.Trim();
                DataTable dts = DataAccess.Instance("BizDB").ExecuteDataTable(sstr);
                string MenuName = dts.Rows[0]["cnname"].ToString().Trim();
                if (MenuName != txtName.Text.Trim())
                {
                    //菜单更改删除以前的数据
                    string str = "delete com_resourcerelation a where a.ext02=(select a.resourceid from com_resource a where a.cnname='" + MenuName + "' and a.type='Menu')";
                    DataAccess.Instance("BizDB").ExecuteNonQuery(str);
                }
            }

            txtResourceId.Text = resourceId.ToString();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + Portal.Resources.lang.SecurityDetail_SaveSuccess + "!');location.href='SecurityList.aspx?Name="+txtName.Text.Trim()+"';", true);

        }

        List<TreeNode> GetAllCheckedNodes(TreeView tv)
        {
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (TreeNode tn in tv.Nodes)
            {
                if (tn.Checked)
                {
                    nodes.Add(tn);
                }
                GetChild(nodes, tn);
            }
            return nodes;
        }

        void GetChild(List<TreeNode> tns, TreeNode tn)
        {
            foreach (TreeNode t in tn.ChildNodes)
            {
                if (t.Checked)
                {
                    tns.Add(t);
                }
                GetChild(tns, t);
            }
        }

        //添加选择项
        protected void addToListBox1_Click(object sender, EventArgs e)
        {
            if (txtMemberId.Text.Trim() != "")
            {
                string[] sme = txtMember.Text.Trim().Split(',');
                string tmi = txtMemberId.Text.Trim().Replace("<+>", "+");
                string[] sid = tmi.Split('+');
                //多选
                if (sme.Length > 1)
                {
                    for (int i = 0; i < sme.Length; i++)
                    {
                        //判断是否重复
                        for (int j = 0; j < lstboxMember.Items.Count; j++)
                        {
                            string temp = lstboxMember.Items[j].Text.Trim();
                            //如果重复
                            if (temp == sme[i])
                            {
                                lstboxMember.Items.Remove(lstboxMember.Items[j]);
                            }

                        }

                        ListItem lm = new ListItem(sme[i], sid[i]);
                        this.lstboxMember.Items.Add(lm);
                        lstboxMember.DataBind();
                    }
                }
                else
                {
                    //当有选择项时
                    if (lstboxMember.Items.Count == 0)
                    {
                        ListItem li = new ListItem(this.txtMember.Text.Trim(), this.txtMemberId.Text.Trim());
                        this.lstboxMember.Items.Add(li);
                        lstboxMember.DataBind();
                    }
                    else
                    {//判断是否重复
                        for (int j = 0; j < lstboxMember.Items.Count; j++)
                        {
                            string temp = lstboxMember.Items[j].Text.Trim();
                            //如果重复
                            if (temp == sme[0])
                            {
                                lstboxMember.Items.Remove(lstboxMember.Items[j]);
                            }
                        }
                        ListItem li = new ListItem(this.txtMember.Text.Trim(), this.txtMemberId.Text.Trim());
                        this.lstboxMember.Items.Add(li);
                        lstboxMember.DataBind();
                    }
                }
            }
        }

        //移除选择项
        protected void btnRemoveItem_Click(object sender, EventArgs e)
        {
            if (lstboxMember.SelectedIndex != -1)
            {
                //删除选中菜单数据
                string name = txtName.Text.Trim();
                if (!string.IsNullOrEmpty(name))
                {
                    int id = 0;
                    //判断是新选择还是已有的加载
                    if (lstboxMember.SelectedItem.Value.Trim().Split('|').Length > 1)
                    {

                        //判断是否为人员
                        if (lstboxMember.SelectedItem.Value.Trim().Split('|')[0].Split('/').Length > 1)
                        {
                            id = Convert.ToInt32(lstboxMember.SelectedItem.Value.Trim().Split('|')[0].Split('/')[1]);
                        }
                        else
                        {
                            id = Convert.ToInt32(lstboxMember.SelectedItem.Value.Trim().Split('|')[0]);
                        }
                    }
                    else {
                        id = Convert.ToInt32(lstboxMember.SelectedItem.Value.Trim().Split('|')[0]);
                    }
                    string str = "delete com_resourcerelation c where c.destinationid=" + id + " and c.ext02=(select a.resourceid from com_resource a where a.cnname='" + name + "' and a.type='Menu')";
                    DataAccess.Instance("BizDB").ExecuteNonQuery(str);
                }
                lstboxMember.Items.Remove(lstboxMember.SelectedItem);
            }
        }
    }
}